class InvoicesController < ApplicationController
  before_action :set_invoice, only: [:show, :edit, :update, :destroy]

  respond_to :html

  def index
    @invoices = Invoice.order(created_at: :desc).page(params[:page])
    respond_with(@invoices)
  end

  def show
    respond_with(@invoice)
  end

  def new    
    @invoice = Invoice.new
    @orders = Array.new    
    
#   Retrieve order_ids from url params
    if params["order_id"].presence  
      puts "order_id :............."
      puts params["order_id"]
      
      if params["order_id"].size == 1
        @invoice.orders_invoices.build
                    
          order = Order.find(params["order_id"])
          @orders.push(order)
      else
        params["order_id"].each do |p|
          @invoice.orders_invoices.build
                    
          order = Order.find(p)
          @orders.push(order)
        end        
      end   
         
    end

    respond_with(@invoice)
  end

  def edit
  end

  def create      
    @invoice = Invoice.new(invoice_params)
    logger.info("orders_invoice items: " )    
    puts @invoice
    puts @invoice.orders_invoices
    
    @orders = Array.new     
    @invoice.orders_invoices.each do  |o|
      puts "order_invoice iterm ..."
      puts o.order_id
      order = Order.find(o.order_id)
      @orders.push(order)
    end
    
    @invoice.save
    
    
    respond_with(@invoice)
  end

  def update
    @invoice.update(invoice_params)
    respond_with(@invoice)
  end

  def destroy
    @invoice.destroy
    respond_with(@invoice)
  end

  


  private
    def set_invoice
      @invoice = Invoice.find(params[:id])
    end

    def invoice_params           
      params.require(:invoice).permit(:invoice_no,:invoice_code, :invoice_index_code, :settlement_slip_no,:amount,:tax_rate,:invoice_date,:customer_id,:payment_progress,:first_installment_amount,:first_installment_date,:balance_amount, :balance_date,orders_invoices_attributes: [:order_id] )
    end
    
end
